package dav

import (
	"math/rand"
	"strconv"
	"tosServer/internal/model"
	"tosServer/internal/pkg/common"
	"tosServer/internal/pkg/db"

	"github.com/gin-gonic/gin"
)

// CreateUser
// @Summary 创建dav账号
// @Tags	dav
// @Param	request body model.CreateDavUser true "request"
// @Success	200  {object}  common.R
// @Router	/dav/create_user [post]
func (d *Dav) CreateUser(c *gin.Context) {

	createDavUser := new(model.CreateDavUser)
	err := c.ShouldBind(createDavUser)
	if err != nil {
		d.Api.Error(c, &common.R{
			Msg: err.Error(),
		})
		return
	}

	minInt := 10000000
	maxInt := 99999999
	salt := strconv.Itoa(rand.Intn(maxInt-minInt+1) + minInt)

	davUser := new(model.DavUser)
	davUser.RoleID = createDavUser.RoleID
	davUser.Password = davUser.EncrypPass(createDavUser.Password, salt)
	davUser.Username = createDavUser.Username
	davUser.Name = createDavUser.Name
	davUser.Salt = salt
	result := db.Db().Table(model.TableNameDavUser).Create(&davUser)

	if result.Error != nil {
		d.Api.Error(c, &common.R{
			Msg: result.Error.Error(),
		})
		return
	}

	davUser.Salt = ""
	davUser.Password = ""

	d.Api.Success(c, &common.R{
		Data: davUser,
	})

}

// UpdateUser
// @Summary 更新dav账号
// @Tags	dav
// @Param	request body model.UpdateDavUser true "request"
// @Success	200  {object}  common.R
// @Router	/dav/update_user [post]
func (d *Dav) UpdateUser(c *gin.Context) {
	updateDavUser := new(model.UpdateDavUser)
	err := c.ShouldBind(updateDavUser)
	if err != nil {
		d.Api.Error(c, &common.R{
			Msg: err.Error(),
		})
		return
	}
	davUser := new(model.DavUser)
	if updateDavUser.RoleID != 0 {
		davUser.RoleID = updateDavUser.RoleID
	}
	if updateDavUser.Name != "" {
		davUser.Name = updateDavUser.Name
	}
	if updateDavUser.Username != "" {
		davUser.Username = updateDavUser.Username
	}
	if updateDavUser.Password != "" {
		minInt := 10000000
		maxInt := 99999999
		davUser.Salt = strconv.Itoa(rand.Intn(maxInt-minInt+1) + minInt)
		davUser.Password = davUser.EncrypPass(updateDavUser.Password, davUser.Salt)
	}

	result := db.Db().Table(model.TableNameDavUser).Where("id", updateDavUser.ID).Updates(&davUser)

	if result.Error != nil {
		d.Api.Error(c, &common.R{
			Msg: result.Error.Error(),
		})
		return
	}

	d.Api.Success(c, &common.R{})

}
